﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;

namespace RedirctDemo2
{
  public enum RequestMode
  {
    None,
    FromHttp2Https,
    FromHttps2Http
  }

  public enum RedirctMode
  {
    MovedPermanently = 301,
    Redirect = 302
  }

  public class RedirctHelper
  {
    public const string Scheme_Http = "http";

    public const string Scheme_Https = "https";

    public static void AutoRedirct(Uri uri = null, RequestMode requestMode = RequestMode.FromHttp2Https, RedirctMode redirctMode = RedirctMode.MovedPermanently, string redirctPath = null)
    {
      string scheme = null;

      uri = uri ?? HttpContext.Current.Request.Url;

      switch (requestMode)
      {
        case RequestMode.None:
          break;
        case RequestMode.FromHttp2Https:
          scheme = Scheme_Http;
          break;
        case RequestMode.FromHttps2Http:
          scheme = Scheme_Https;
          break;
        default:
          break;
      }

      if (string.IsNullOrEmpty(scheme))
      {
        return;
      }

      if (uri.Scheme.Equals(scheme, StringComparison.CurrentCultureIgnoreCase))
      {
        var redirct = redirctPath ?? string.Format("{0}://{1}{2}", scheme.Equals(Scheme_Http) ? Scheme_Https : Scheme_Http, uri.Authority, uri.PathAndQuery);

        switch (redirctMode)
        {
          case RedirctMode.MovedPermanently:
            Redirect301(redirct);
            break;
          case RedirctMode.Redirect:
            Redirect302(redirct);
            break;
        }
      }
    }

    public static void Redirect301(string redirct)
    {
      var response = HttpContext.Current.Response;

      response.StatusCode = Convert.ToInt32(HttpStatusCode.MovedPermanently);
      response.Status = "301 Moved Permanently";
      response.AppendHeader("Location", redirct);
      response.AppendHeader("Cache-Control", "no-cache");
      response.End();
    }

    public static void Redirect302(string redirct)
    {
      var response = HttpContext.Current.Response;

      response.Redirect(redirct, true);
    }
  }
}